package com.mymoney.persistence.managers;

import java.util.List;

import javax.persistence.EntityManager;
import javax.persistence.Query;

import com.mymoney.exceptions.MyMoneyException;
import com.mymoney.persistence.PersistenceContext;

/**
 * 
 * @author yavor.gologanov
 *
 */
public abstract class AbstractBeanManager<T> {

	private PersistenceContext persistenceContext = null;

	protected AbstractBeanManager(PersistenceContext persistenceContext) {
		this.persistenceContext = persistenceContext;
	}

	public abstract void add(T entity)  throws MyMoneyException;
	
	public abstract List<T> list() throws MyMoneyException;
	
	public abstract T getByCode(long code) throws MyMoneyException;
	
	public abstract T getById(Integer id) throws MyMoneyException;
	
	public abstract T getByName(String name) throws MyMoneyException;
	
	public abstract void update(T first, T second) throws MyMoneyException;
	
	public abstract void update(T entity, long code) throws MyMoneyException;
	
	public abstract void update(T entity, Integer id) throws MyMoneyException;
	
	public abstract void update(T entity, String name) throws MyMoneyException;
	
	@SuppressWarnings("unchecked")
	public T getBy(String pQuery, Object pValue, String pName)
	{
		T entity = null;
		
		try
		{
			Query query = getEntityManager().createQuery(pQuery);
			query.setParameter(pName, pValue);
			entity = (T) query.getSingleResult();
		}catch (Exception e) {
			e.printStackTrace();
		}
		
		return entity;
	}
	
	protected EntityManager getEntityManager() {
		return persistenceContext.getEntityManager();
	}

	protected PersistenceContext getPersistenceContext() {
		return persistenceContext;
	}

	protected void storeEntity(T entity) {

		getEntityManager().persist(entity);
		//getEntityManager().flush();

	}
	

	@SuppressWarnings("unchecked")
	protected List<T> findAllEntities(String selectQuery, int limit, Object... parameters) {

		Query query = getEntityManager().createQuery(selectQuery);
		if (parameters != null  && parameters.length > 0) {
			for (int i = 0; i < parameters.length; i += 2) {
				String parameterName = (String)parameters[i];
				Object parameterValue = parameters[i + 1];

				query.setParameter(parameterName, parameterValue);
			}
		}
		if(limit > 0) {
			query.setMaxResults(limit);
		}

		return (List<T>) query.getResultList();

	}
}
